package crack.transformer;

import javassist.*;

import java.io.*;
import java.security.ProtectionDomain;

public class Class2FileTransformer extends CrackTransformer {

  public Class2FileTransformer(String targetName, String methodName, String funBody, boolean isNative) {
    super(targetName, methodName, funBody, isNative);
  }

  @Override
  protected byte[] modifyMethod(byte[] classfileBuffer, String methodName, int stack, int locals, byte[] newCode, String targetName, String funBody, boolean isNative) throws Exception {
    return loadHackClassBuffer2(targetName, methodName, funBody, isNative);
  }


  private byte[] loadHackClassBuffer(ClassLoader loader, String filename) {
    //反编译 -> 修改 -> 重新编译的LicenseVerifier.class 文件，换个后缀防止被JVM自动加载
    try (InputStream input = loader.getResourceAsStream("LicenseVerifier.classdata")) {
      int n;
      ByteArrayOutputStream outputBuffer = new ByteArrayOutputStream();
      byte[] buffer = new byte[4096];//4k
      //-1 : end of file
      while (-1 != (n = input.read(buffer))) {
        outputBuffer.write(buffer, 0, n);
      }
      return outputBuffer.toByteArray();
    } catch (IOException e) {
      System.err.println("load the hackfile failed!");
      return null;
    }
  }

  private byte[] loadHackClassBuffer2(String targetName, String methodName, String body, boolean isNative) {
    byte[] re = null;
    try {
      System.out.println("进入了loadHackClassBuffer2");
      ClassPool pool = ClassPool.getDefault();

      CtClass ctClass = pool.get(targetClassName.replace('/', '.'));
      CtMethod method = ctClass.getDeclaredMethod(methodName);
      // 修改方法的访问标志，移除native属性
      if (isNative) {
        method.setModifiers(method.getModifiers() & ~Modifier.NATIVE);
      }
      // 提供普通方法的实现
      method.setBody(body);
      re = ctClass.toBytecode();
      System.out.println("修改成功了 targetName="+targetName+"methodName="+methodName);
    } catch (Exception e) {
      System.out.println("失败原因："+e.getMessage());
    }
    return re;
  }


}
